import IconDouyin from '@/components/icon/IconDouyin';
import { selectMonitorVideoRecord } from '@/services/api/api-monitor-video';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { ProCard, ProFormRadio } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import {
  Card,
  Col,
  Descriptions,
  Divider,
  Row,
  Select,
  Space,
  Spin,
  Tabs,
  Tag,
  Typography,
  message,
} from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import ModalResolve from '../../linkage/components/ModalResolve';
import { selectMonitorhcRecord } from '@/services/api/api-monitor-article';
import DetailMonitorDisposeContent from '../../dispose/DetailMonitorDisposeContent';

interface DetailMonitorVideoProps {
  data: MonitorArticleData.RecordPage;
  onRefurbish: () => void;
  triggerMode: 'card' | 'title';
  isLinkage: boolean;
}

const DetailMonitorVideo: React.FC<DetailMonitorVideoProps> = ({
  data,
  onRefurbish,
  triggerMode,
  isLinkage,
}) => {
  const access = useAccess();
  const videoRef = useRef<HTMLVideoElement>(null);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState('tab1');
  const [details, setDetailDataState] = useState<MonitorArticleData.RecordSelect>();
  const [sensitives, setSensitives] = useState([]);

  const getDetailData = async () => {
    const response = await selectMonitorhcRecord({ id: data.id });
    if (response.code == 0) {
      setDetailDataState(response.data);
      setSensitives(response.data?.greenVideo || []);
      onRefurbish();
    }
  };

  // 统一的跳转时间函数
  const jumpToTime = (timeString: string) => {
    if (!videoRef.current) {
      message.error('视频未加载完成，请稍后再试');
      return;
    }

    try {
      // 处理时间格式，支持多种格式
      let time = moment(timeString, ['HH:mm:ss', 'mm:ss', 'HH:mm:ss.SSS']);

      if (!time.isValid()) {
        message.error(`时间格式无效: ${timeString}`);
        return;
      }

      // 计算总秒数
      const timestamp = time.diff(moment().startOf('day'), 'seconds');

      if (!isFinite(timestamp) || timestamp < 0) {
        message.error(`计算出的时间戳无效: ${timestamp}`);
        return;
      }

      // 设置视频时间
      videoRef.current.currentTime = timestamp;

      // 格式化显示时间
      const formattedTime = time.format('HH:mm:ss');
      message.success(`跳转到 ${formattedTime}`);
    } catch (error) {
      console.error('跳转时间出错:', error);
      message.error('跳转失败，请检查时间格式');
    }
  };

  // 处理标签点击事件
  const handleTagClick = (timeString: string) => {
    // 如果当前不在视频tab，先切换到视频tab
    if (tab !== 'tab1') {
      setTab('tab1');
      // 等待tab切换完成后再跳转
      setTimeout(() => {
        jumpToTime(timeString);
      }, 100);
    } else {
      jumpToTime(timeString);
    }
  };

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            详情
            {data.violationLevel == undefined || data.violationLevel == 0 ? (
              <Tag icon={<CheckCircleOutlined />} color={'success'}>
                正常
              </Tag>
            ) : data.violationLevel == 1 ? (
              <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                {'警告'}
              </Tag>
            ) : data.violationLevel == 2 ? (
              <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                {'问题'}
              </Tag>
            ) : (
              <Tag icon={<CloseCircleOutlined />} color={'error'}>
                {'告警'}
              </Tag>
            )}
          </div>
          {isLinkage && (
            <div>
              {details?.disposeState === 1 ? (
                <></>
              ) : details?.disposeState === 2 ? (
                <ModalResolve id={details?.id} onRefurbish={getDetailData} />
              ) : details?.disposeState === 3 ? (
                <DetailMonitorDisposeContent data={details} onRefurbish={() => {}} />
              ) : null}
            </div>
          )}
        </div>
      }
      drawerProps={{
        destroyOnClose: true,
        width: '100%',
      }}
      trigger={
        triggerMode === 'card' ? (
          <div
            style={{
              paddingLeft: 10,
              paddingRight: 10,
              paddingBottom: 10,
            }}
          >
            <Card
              bordered={false}
              hoverable
              style={{
                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
              }}
            >
              <Card.Meta
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between', width: '73vw' }}>
                    <div
                      style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        minWidth: 65,
                      }}
                    >
                      {data?.dataName}
                    </div>
                    <div
                      style={{
                        float: 'left',
                      }}
                    >
                      {!isLinkage ? (
                        <div>
                          {data.violationLevel == undefined || data.violationLevel == 0 ? (
                            <Tag icon={<CheckCircleOutlined />} color={'success'}>
                              正常
                            </Tag>
                          ) : data.violationLevel == 1 ? (
                            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                              {'警告'}
                            </Tag>
                          ) : data.violationLevel == 2 ? (
                            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                              {'问题'}
                            </Tag>
                          ) : (
                            <Tag icon={<CloseCircleOutlined />} color={'error'}>
                              {'告警'}
                            </Tag>
                          )}
                        </div>
                      ) : (
                        <Tag
                          icon={
                            data?.disposeState == 1 ? (
                              <QuestionCircleOutlined />
                            ) : data?.disposeState == 2 ? (
                              <ExclamationCircleOutlined />
                            ) : (
                              <CheckCircleOutlined />
                            )
                          }
                          color={
                            data?.disposeState == 1
                              ? 'processing'
                              : data?.disposeState == 2
                              ? '#f50'
                              : 'success'
                          }
                        >
                          {data?.disposeState == 1
                            ? '不需要处置'
                            : data?.disposeState == 2
                            ? '需要处置'
                            : '处置完成'}
                        </Tag>
                      )}
                    </div>
                  </div>
                }
                description={
                  <>
                    <div>
                      <div>平台 :{data.datahubChannelName}</div>
                      <div>账号 : {data.datahubSourceName}</div>
                      <div>
                        单位 :
                        {data.auditSourceResponsibles
                          .map((item) => item.responsibleOrganizationName)
                          .join('/')}
                      </div>
                    </div>
                    <div
                      style={{
                        marginTop: 5,
                        marginRight: 18,
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '100%',
                      }}
                    >
                      <span>发布时间:{data?.dataReleaseTime}</span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      ></span>
                    </div>
                  </>
                }
              />
            </Card>
            <div
              style={{
                borderRadius: 12,
                background: '#FFF',
              }}
            ></div>
          </div>
        ) : (
          <a>{details?.dataName}</a>
        )
      }
      onVisibleChange={async (visible) => {
        if (visible) {
          getDetailData();
        }
      }}
      submitter={false}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        {details !== undefined && (
          <div style={{ overflow: 'hidden' }}>
            <Descriptions title="文章信息" column={1}>
              <Descriptions.Item label="文章标题">{details?.dataName}</Descriptions.Item>
              <Descriptions.Item label="平台">{details.datahubChannelName}</Descriptions.Item>
              <Descriptions.Item label="账号">{details?.datahubSourceName}</Descriptions.Item>
              <Descriptions.Item label="发布时间">{details?.dataReleaseTime}</Descriptions.Item>
              <Descriptions.Item label="查看原文">
                <a href={details?.dataUrl} target="_blank" style={{ width: '90%' }}>
                  <Typography.Paragraph copyable ellipsis>
                    {details?.dataUrl}
                  </Typography.Paragraph>
                </a>
              </Descriptions.Item>
            </Descriptions>
            <Divider />
            <Descriptions title="相关负责人" column={1}>
              {details.auditSourceResponsibles &&
                details.auditSourceResponsibles.map((item, index) => {
                  return (
                    <React.Fragment key={index}>
                      <Descriptions.Item label="负责人">
                        {item.responsibleAccountName}
                      </Descriptions.Item>
                      <Descriptions.Item label="负责人联系方式">
                        {item?.responsibleAccountPhone}
                      </Descriptions.Item>
                      <Descriptions.Item label="负责单位">
                        {item?.responsibleOrganizationName}
                      </Descriptions.Item>
                    </React.Fragment>
                  );
                })}
            </Descriptions>
            <Divider />
            <Tabs activeKey={tab} onChange={setTab}>
              <Tabs.TabPane tab="视频信息" key="tab1">
                <video
                  ref={videoRef}
                  style={{
                    width: '100%',
                    height: 500,
                    display: loading ? 'none' : 'block',
                  }}
                  controls
                  src={details?.dataUrl}
                  onLoadStart={() => setLoading(true)}
                  onLoadedData={() => setLoading(false)}
                  onError={() => {
                    setLoading(false);
                  }}
                />
                {loading && (
                  <div
                    style={{
                      width: '100%',
                      height: 500,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      background: '#f5f5f5',
                    }}
                  >
                    <Spin size="large" tip="视频加载中..." />
                  </div>
                )}
              </Tabs.TabPane>
              <Tabs.TabPane tab="错误信息" key="tab2">
                <ProFormRadio.Group
                  name="levelId"
                  radioType="button"
                  initialValue={'all'}
                  options={[
                    { label: '全部', value: 'all' },
                    { label: '视频', value: 'p' },
                    { label: '音频', value: 'a' },
                    { label: '其他', value: 'other' },
                  ]}
                  fieldProps={{
                    onChange: (e) => {
                      let value = e.target.value;
                      if (value === 'p') {
                        const list =
                          details?.greenVideo?.filter((item) => item?.type === 'p') || [];
                        setSensitives(list);
                      } else if (value === 'a') {
                        const list =
                          details?.greenVideo?.filter((item) => item?.type === 'a') || [];
                        setSensitives(list);
                      } else {
                        setSensitives(details.greenVideo || []);
                      }
                    },
                  }}
                />
                <ProList<any>
                  ghost
                  dataSource={sensitives}
                  pagination={false}
                  itemLayout="vertical"
                  onItem={(record: any) => {
                    return {
                      onClick: () => {
                        if (record.appearTime) {
                          handleTagClick(record.appearTime);
                        }
                      },
                    };
                  }}
                  metas={{
                    title: {
                      render: (dom: React.ReactNode, item: any) =>
                        item?.name ? (
                          <div style={{ fontSize: 15 }}>{item?.name}</div>
                        ) : (
                          <div style={{ fontSize: 15 }}>音频链接</div>
                        ),
                    },
                    extra: {
                      render: (dom: React.ReactNode, item: any) =>
                        item?.pictureUrl ? (
                          <img width={152} height={100} alt="图片" src={item?.pictureUrl} />
                        ) : (
                          <></>
                        ),
                    },
                    description: {
                      render: (dom: React.ReactNode, item: any) => {
                        if (item.type == 'p') {
                          return (
                            <>
                              <Descriptions title={item?.name} column={1}>
                                <Descriptions.Item label="职务">{item.position}</Descriptions.Item>
                                <Descriptions.Item label="相似度">
                                  {item.similarity}
                                </Descriptions.Item>
                                <Descriptions.Item label="出现时间">
                                  <Space wrap>
                                    {item.appearTimes?.map((time: string, index: number) => (
                                      <Tag
                                        key={index}
                                        onClick={(e) => {
                                          e.stopPropagation(); // 阻止事件冒泡
                                          handleTagClick(time);
                                        }}
                                        style={{ cursor: 'pointer' }}
                                      >
                                        {moment(time, 'HH:mm:ss').format('HH:mm:ss')}
                                      </Tag>
                                    ))}
                                  </Space>
                                </Descriptions.Item>
                              </Descriptions>
                            </>
                          );
                        } else {
                          return (
                            <Descriptions title={item?.name} column={1}>
                              <Descriptions.Item label="词汇">
                                <Space wrap>
                                  {item.keyWords?.map((keyWord: string, index: number) => (
                                    <Tag key={index}>{keyWord}</Tag>
                                  ))}
                                </Space>
                              </Descriptions.Item>
                              <Descriptions.Item label="出现时间">
                                <Space wrap>
                                  {item.appearTimes?.map((time: string, index: number) => (
                                    <Tag
                                      key={index}
                                      onClick={(e) => {
                                        e.stopPropagation(); // 阻止事件冒泡
                                        handleTagClick(time);
                                      }}
                                      style={{ cursor: 'pointer' }}
                                    >
                                      {moment(time, 'HH:mm:ss').format('HH:mm:ss')}
                                    </Tag>
                                  ))}
                                </Space>
                              </Descriptions.Item>
                            </Descriptions>
                          );
                        }
                      },
                    },
                    content: {
                      render: (dom: React.ReactNode, item: any) => {
                        return (
                          <Typography>
                            <Typography.Text type="secondary">
                              {item?.position}
                              {item?.content}
                            </Typography.Text>
                          </Typography>
                        );
                      },
                    },
                  }}
                />
              </Tabs.TabPane>
            </Tabs>
          </div>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailMonitorVideo;
